package one.stand.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import one.stand.feign.CrmFegin;
import one.stand.feign.LoginFegin;
import one.stand.feign.UserFeign;
import one.stand.util.ChannelGroupUtil;
import one.stand.util.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author Administrator
 */
@Component
public class BaseService {
    protected Logger log = LoggerFactory.getLogger(BaseService.class);
    @Autowired
    protected RedisUtil redisUtil;

    @Autowired
    protected LoginFegin loginFegin;
    @Autowired
    protected CrmFegin crmFegin;
    @Autowired
    protected UserFeign userFeign;

    protected Date currDate() {
        return new Date();
    }

    /**
     * 消息发送接口
     * @param ctx
     * @param t
     */
    protected <T>void send(ChannelHandlerContext ctx, T t){
        send(ctx.channel(),new TextWebSocketFrame(removeJson(t).toJSONString()));
    }
    /**
     * 消息发送接口
     * @param ctx
     * @param t
     */
    protected <T>void send(Channel ctx, T t){
        send(ctx,new TextWebSocketFrame(removeJson(t).toJSONString()));
    }
    private <T>JSONObject removeJson(T t){
        JSONObject jsonObject= (JSONObject) JSON.toJSON(t);
        jsonObject.remove("id");
        jsonObject.remove("token");
        return jsonObject;
    }

    public void send(Channel ctx,TextWebSocketFrame textWebSocketFrame){
        log.info("发送消息："+textWebSocketFrame.text());
        ctx.writeAndFlush(textWebSocketFrame);
    }

    /**
     * 通道关闭
     * @param ctx
     */
    public void close(ChannelHandlerContext ctx){
        ChannelGroupUtil.timerMap.remove(ctx.channel().id().asLongText());
        ChannelGroupUtil.channelMap.remove(ctx.channel().id().asLongText());
        ChannelGroupUtil.channelGroup.remove(ctx.channel());
        ctx.close();
    }
}
